package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.exception.YyghException;
import com.atguigu.yygh.hosp.repository.HospitalMongoDbRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.result.R;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/3/15 22:36
 */
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalMongoDbRepository hospitalMongoDbRepository;
    @Autowired
    private DictFeignClient dictFeignClient;

    //保存到mongoDB
    @Override
    public void saveHospital(Map<String, Object> map) {
        //将map转成实体类
        String jsonString = JSONObject.toJSONString(map);
        //医院方传过来的hospital对象(无状态,创建时间等信息)
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);
        //base64解码在传输过程这自动将+转成空格，需要转回来
        String base64LogoData = hospital.getLogoData().replaceAll(" ", "+");
        hospital.setLogoData(base64LogoData);
        //判断是否存在
        Hospital hospitalByHoscode = hospitalMongoDbRepository.findHospitalByHoscode(hospital.getHoscode());
        if (hospitalByHoscode != null) {
            //存在，更新
            hospital.setStatus(hospitalByHoscode.getStatus());
            hospital.setCreateTime(hospitalByHoscode.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(hospitalByHoscode.getIsDeleted());
            hospital.setId(hospitalByHoscode.getId());//根据id更新
            hospitalMongoDbRepository.save(hospital);
        } else {
            //不存在，新增
            //id由mongoDB自动生成
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            //value = "状态 0：未上线 1：已上线"
            hospital.setStatus(0);
            //value = "逻辑删除(1:已删除，0:未删除)"
            hospital.setIsDeleted(0);
            hospitalMongoDbRepository.save(hospital);
        }
    }

    @Override
    public Hospital findHospitalByHoscode(Map<String, Object> map) {
        String hoscode = (String) map.get("hoscode");
        Hospital hospitalByHoscode = hospitalMongoDbRepository.findHospitalByHoscode(hoscode);
        return hospitalByHoscode;
    }

    @Override
    public Hospital findHospitalByHoscode(String hoscode) {
        Hospital hospital = hospitalMongoDbRepository.findHospitalByHoscode(hoscode);
        packHospital(hospital);
        return hospital;
    }

    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Hospital> hospitalExample = Example.of(hospital, matcher);
        PageRequest pageRequest = PageRequest.of(page - 1, limit, Sort.Direction.ASC, "createTime");
        Page<Hospital> all = hospitalMongoDbRepository.findAll(hospitalExample, pageRequest);
        //查出来的Value值是数字,需要远程调用cmn模块进行转换
        all.getContent().stream().forEach(item -> {
            this.packHospital(item);
        });
        return all;
    }

    @Override
    public void changeStatus(String id, Integer status) {
        if (status == 0 || status == 1) {
            //先查出Hospital对象
            Hospital hospital = hospitalMongoDbRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalMongoDbRepository.save(hospital);
        } else {
            throw new YyghException(20001, "状态值错误");
        }

    }

    @Override
    public Hospital selectById(String id) {
        Hospital hospital = hospitalMongoDbRepository.findById(id).get();
        packHospital(hospital);
        return hospital;
    }

    @Override
    public String getHospitalName(String hoscode) {
        Hospital hospitalByHoscode = hospitalMongoDbRepository.findHospitalByHoscode(hoscode);

        return hospitalByHoscode.getHosname();
    }

    @Override
    public List<Hospital> selectByNameLike(String name) {
        return hospitalMongoDbRepository.findHospitalByHosnameLike(name);

    }

    @Override
    public BookingRule getBoookingRule(String hoscode) {
        return hospitalMongoDbRepository.findHospitalByHoscode(hoscode).getBookingRule();
    }


    private void packHospital(Hospital item) {
        // 远程调用cmn模块进行转换
        String provinceCode = item.getProvinceCode();
        String cityCode = item.getCityCode();
        String districtCode = item.getDistrictCode();
        String province = dictFeignClient.getName(provinceCode);
        String city = dictFeignClient.getName(cityCode);
        String district = dictFeignClient.getName(districtCode);

        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), item.getHostype());

        item.getParam().put("hostypeString", hostypeString);
        item.getParam().put("fullAddress", province + city + district + item.getAddress());
    }
}
